package edu.ncut.vod.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import edu.ncut.vod.commonbeans.JSmartComFileUpload;

public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = -8057047330634621261L;
    
    /*
     * 
     */
    private List<JSmartComFileUpload> uploadedFile; 
    
    /**
     * @return the uploadedFile
     */
    public List<JSmartComFileUpload> getUploadedFile() {
        if(null == uploadedFile){
            uploadedFile = new ArrayList<JSmartComFileUpload>();
        }
        return uploadedFile;
    }

    /**
     * @param uploadedFile the uploadedFile to set
     */
    public void setUploadedFile(List<JSmartComFileUpload> uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

    /**
     * Constructor of the object.
     */
    public FileUploadServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log

    }

    /**
     * The doDelete method of the servlet. <br>
     * 
     * This method is called when a HTTP delete request is received.
     * 
     * @param request:the request send by the client to the server
     * @param response:the response send by the server to the client
     * @throws ServletException:if an error occurred
     * @throws IOException:if an error occurred
     */
    public void doDelete(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * 
     * @param request:servlet request
     * @param response:servlet response
     */
    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        /*
         * pay attention:
         * Codes are processed in servlet file,so we need object 'ServletConfig' as parameter 
         * to call method 'initiate' of object 'SmartUpload'.
         * If codes are peocessed at
         * JSP file,we only need use object 'pageContext' as parameter to call method 'initiate' 
         * of object 'SmartUpload'.
         * At JSP file,codes are as follows:
         * SmartUpload su = new SmartUpload();
         * su.initialize(pageContext);
         */
        
        /*
         * public ServletConfig getServletConfig():Returns this servlet's ServletConfig object.
         */
        ServletConfig config = getServletConfig();

        /*
         * public SmartUpload():SmartUpload Creates an new SmartUpload instance.
         */
        SmartUpload su = new SmartUpload();

        /*
         * public final void initialize(javax.servlet.ServletConfig config,
         * javax.servlet.http.HttpServletRequest request,
         * javax.servlet.http.HttpServletResponse response) throws
         * javax.servlet.ServletException
         * Initialize the object with implicits objects. This method always must be called 
         * in first. This method is meant to be used when the component is called from 
         * a servlet (not a JSP page).
         */
        su.initialize(config, request, response);

        try {
            /*
             * public void upload() throws javax.servlet.ServletException,
             * java.io.IOException, SmartUploadException
             * upload Uploads data from the form.
             */
            su.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        
        /*
         * upload file and store them at given directory.
         */
        int count;
        try {
            count = su.save("/upload/");
            debug(count + "个文件上传成功!<br>");
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

        /*
         * get information about upload file and print them on browser.
         */
        for (int i = 0; i < su.getFiles().getCount(); i++) {
            com.jspsmart.upload.File file = su.getFiles().getFile(i);
            
            /*
             * public boolean isMissing():Test if a file is present.
             */
            if (file.isMissing())
                continue;
                        
            JSmartComFileUpload jscfu = new JSmartComFileUpload();
            
            jscfu.setFieldName(file.getFieldName());
            //debug(jscfu.getFieldName());
            jscfu.setSize(file.getSize());
            jscfu.setFileName(file.getFileName());
            //debug(file.getFileName());
            jscfu.setFileExt(file.getFileExt());
            jscfu.setFilePathName(file.getFilePathName());
            
            getUploadedFile().add(jscfu);
            //debug(getUploadedFile().get(i).getFileName());                        
        }
        request.getSession().setAttribute("uploadedFile",getUploadedFile());       
        request.getRequestDispatcher("/pages/index.jsp").forward(request,response);
    }

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request:the request send by the client to the server
     * @param response:the response send by the server to the client
     * @throws ServletException:if an error occurred
     * @throws IOException:if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request:the request send by the client to the server
     * @param response:the response send by the server to the client
     * @throws ServletException:if an error occurred
     * @throws IOException:if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * The doPut method of the servlet. <br>
     * 
     * This method is called when a HTTP put request is received.
     * 
     * @param request:the request send by the client to the server
     * @param response:the response send by the server to the client
     * @throws ServletException:if an error occurred
     * @throws IOException:if an error occurred
     */
    public void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    /**
     * Returns information about the servlet, such as author, version, and copyright.
     * 
     * @return String information about this servlet
     */
    public String getServletInfo() {
        return "This is my default servlet created by Eclipse";
    }

    /**
     * Initialization of the servlet. <br>
     * 
     * @throws ServletException:if an error occurs
     */
    public void init() throws ServletException {

    }

    /**
     * print mesage in console
     * @param message
     */
    public static void debug(String message) {
        System.out.println(message);
    }
}
